package com.wanglibao.woodtrade.woodtrade.service;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.MyApplication;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.Version;
import com.wanglibao.woodtrade.woodtrade.ui.activity.HomeActivity;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by ybli on 2015/8/11.
 */
@SuppressLint("HandlerLeak")
public class UpdateService {
    @SuppressWarnings("rawtypes")
	private Version version;
    private String mSavePath; /* 下载保存路径 */
    private Activity mContext;
    private ProgressBar mProgress;  /* 更新进度条 */
    private Dialog mDownloadDialog;
    
    private NotificationManager manager;  
    private Notification notif;
    private RemoteViews RemoteViews;
    private PendingIntent pendingIntent;
    
    private Intent updateIntent;

    /* 下载中 */
    private static final int DOWNLOAD = 1;

    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;

    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    /* 记录进度条数量 */
    private int progress;

    boolean isShowDialog = false;

    public UpdateService(Activity mContext) {
        this.mContext = mContext;
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2) {
                if (msg.arg1 == NetConfig.TaskId.get_version){
                    Gson gson = new Gson();
                    version = gson.fromJson(msg.obj.toString(), Version.class);
                    String versionNum = version.getInfo().getVersion_no();
                    PackageManager packageManager = mContext.getPackageManager();
                    try {
                        PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
                        String versionName = packageInfo.versionName;
                        if (!versionNum.equals("v"+versionName)) {
                            showUpdateNoticeDialog();
                        } else {
                            if (isShowDialog){
                                ToastUtil.createNormalToast("当前已是最新版本");
                            }
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            return false;
        }
    });

    /**
     * 检查APP版本，版本低时弹出下载对话框
     */
    public void checkAppVersion(boolean isShow) {
        isShowDialog = isShow;
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(false,mContext, NetConfig.SERVER+NetConfig.TYPE_COMMON,
                NetConfig.get_version, handler,"jsonObject",NetConfig.TaskId.get_version,new Object[]{});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    // 构造对话框
    private void showUpdateNoticeDialog() {
        final Dialog noticeDialog = new Builder(mContext).create();
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.show();
        noticeDialog.getWindow().setContentView(R.layout.dialog_app_update);

        Button btn_app_update_dialog_ok = (Button)noticeDialog.findViewById(R.id.btn_app_update_dialog_ok);
        Button btn_app_update_dialog_cancel = (Button)noticeDialog.findViewById(R.id.btn_app_update_dialog_cancel);
        TextView tv_app_update_dialog_message = (TextView)noticeDialog.findViewById(R.id.tv_app_update_dialog_message);
        String versionInfo = version.getInfo().getContent();
        if (versionInfo != null && !"".equals(versionInfo)) {
            tv_app_update_dialog_message.setText(Html.fromHtml(versionInfo));
        }
        // 更新
        btn_app_update_dialog_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                noticeDialog.dismiss();
                ((MyApplication)mContext.getApplicationContext()).downCode = 1;
                ToastUtil.createLongToast(mContext, "开始下载");
                showDownloadProcessDialog(); // 显示下载对话框
            }
        });

        btn_app_update_dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noticeDialog.dismiss();
            }
        });
    	
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
    	((MyApplication)mContext.getApplicationContext()).downCode = 0;
        File file = new File(mSavePath + version.getInfo().getVersion_no());
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);//执行动作
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");//执行的数据类型
        mContext.startActivity(intent);
    	manager.cancelAll();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                	notif.contentView.setProgressBar(R.id.progressBar_notification_progress, 100, progress, false);
                	manager.notify(0, notif);
                    break;
                case DOWNLOAD_FINISH:
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 显示软件下载对话框
     */
    private void showDownloadProcessDialog() {
    	updateIntent = new Intent(mContext,HomeActivity.class);
    	updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    	pendingIntent = PendingIntent.getActivity(mContext, 0, updateIntent, 0);
    	
    	manager = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
        notif = new Notification();
        notif.icon = R.mipmap.icon;
        notif.tickerText = "开始下载";
        
        RemoteViews= new RemoteViews(mContext.getPackageName(), R.layout.notification_layout);
        RemoteViews.setProgressBar(R.id.progressBar_notification_progress, 100, 0, false);
        
        notif.contentView = RemoteViews;
        notif.contentIntent = pendingIntent;
        manager.notify(0, notif);

        downloadApkThread task = new downloadApkThread();
        task.start();
    }

    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获取SD卡路径
                    mSavePath = Environment.getExternalStorageDirectory() + "/download/";
                    File file = new File(mSavePath);
                    // 如果SD卡目录不存在创建
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    URL url = new URL(version.getInfo().getUrl());
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File apkFile = new File(mSavePath + version.getInfo().getVersion_no());
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    int lastProgress = 0;
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        if (progress != lastProgress || progress == 100) {
                        	lastProgress = progress;
                        	 mHandler.sendEmptyMessage(DOWNLOAD);
                             if (numread <= 0) {
                                 // 下载完成
                                 mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                 break;
                             }
						}
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 取消下载对话框显示
                if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
                    mDownloadDialog.dismiss();
                }
            }

        }
    }
}
